package com.beiye.drivertransport.SubActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.Video.MyJZVideoPlayerStandard;
import com.beiye.drivertransport.activity.TwoBaseAty;
import com.beiye.drivertransport.adapter.CourseDetailRvSubjectApt;
import com.beiye.drivertransport.bean.CourseDetailBean;
import com.beiye.drivertransport.bean.CourseDetailSubjectBean;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.thirdparty.tbs.SuperFileView2;
import com.beiye.drivertransport.utils.FileParseUtil;
import com.beiye.drivertransport.utils.ImageJavascriptInterface;
import com.beiye.drivertransport.utils.JSImgUtil;
import com.beiye.drivertransport.utils.LogUtils;
import com.beiye.drivertransport.utils.MusicUtils;
import com.beiye.drivertransport.view.CircularProgressView;
import com.githang.statusbar.StatusBarCompat;
import com.squareup.picasso.Picasso;

import net.frakbot.jumpingbeans.JumpingBeans;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import cn.jzvd.JZDataSource;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

//日常培训课程学习界面查看记录
public class SpecifiedLearningCourseDetailsAgainActivity extends TwoBaseAty implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnPreparedListener {

    WebView web;

    LinearLayout le_parement;

    ImageView img_Courseback;
//    @Bind(R.id.lv_coursedetail)
//    LinearListView lv_coursedetail;

    RecyclerView lv_coursedetail;

    MyJZVideoPlayerStandard jcVideoPlayerStandard;

    TextView tv_courseName;

    TextView tv_courseLength;

    TextView tv_cumulativeLength;//累计时长

    ImageView show_camera_iv;//显示照片

    ImageView show_camera_iv1;//显示照片
    //    @Bind(R.id.id_area_sv)
//    SurfaceView surfaceSv;//预览照片

    TextView tv_sure;//提交

    TextView tv_save;//中途保存

    RelativeLayout re_course;//隐藏按钮

    LinearLayout re_course1;//照片布局

    TextView img_course;

    TextView tv_course11;//请回答

    RelativeLayout re_course2;//隐藏语音

    ImageView playOrPauseFab;//播放

    SeekBar musicSeekBar;//

    TextView tv_playorpause;//播放与暂停显示

    TextView progress_tv;//播放进度时间

    TextView total_tv;//播放总时间

    ScrollView scroll_view;

    LinearLayout le_course2;

    TextView tv_course13;

    TextView tv_course14;

    SuperFileView2 mSuperFileView;
    private PopupWindow mDownloadPopWindow;
    private JumpingBeans jumpingBeans2;

    private MediaPlayer mediaPlayer;
    private MusicHandler musicHandler;
    private TimerTask timerTask;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            if (what == 0) {
                timerTask = new TimerTask() {
                    int cnt = 1;

                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String stringTime = getStringTime(cnt++);
                                tv_cumulativeLength.setText(stringTime);
                                LogUtils.e("format", stringTime);
                                SharedPreferences sp1 = getSharedPreferences("SpecifiedLearningCourseDetailsAgainActivity",
                                        Context.MODE_PRIVATE);
                                int courseLength = sp1.getInt("courseLength", 0);
                                int courseLengthtime = courseLength * 60;
                                String courseLengthtime1 = getStringTime(courseLengthtime);
                                if (stringTime.equals(courseLengthtime1)) {
                                    timerTask.cancel();
                                }
                            }
                        });
                    }
                };
                timer1.schedule(timerTask, 0, 1000);


            }
//            else if (what == 1) {
//                WebSettings settings = web.getSettings();
//                // 允许使用脚本语言
//                settings.setJavaScriptEnabled(true);
//                // 支持缩放
//                settings.setSupportZoom(true);
//                //  mWebView.addJavascriptInterface(new JavaScriptinterface(BannerItemAty.this), "android");
//                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
//                    settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
//                }//Android 5.0中使用webView 加载网页不显示图片问题
//
//                // 在当前应用加载网页(直接加载网页不经过浏览器）
//                web.setWebViewClient(new WebViewClient() {
//                    @Override // 开始加载网页时触发
//                    public void onPageStarted(WebView view, String url, Bitmap favicon) {
//                        super.onPageStarted(view, url, favicon);
//
//                    }
//
//                    @Override // 网页加载完成之后触发
//                    public void onPageFinished(WebView view, String url) {
//
//                        super.onPageFinished(view, url);
//
//                    }
//                });
//                SharedPreferences sp = getSharedPreferences("SpecifiedLearningCourseDetailsAgainActivity",
//                        Context.MODE_PRIVATE);
//                int tcsn = sp.getInt("tcsn", 0);
//                web.loadUrl(AppInterfaceConfig.BASE_URL + "app/course/content?" + "sn=" + tcsn);
//
//                // 显示进度
//                web.setWebChromeClient(new WebChromeClient() {
//                    @Override // 加载网页进度改变时触发
//                    public void onProgressChanged(WebView view, int newProgress) {
//
//                        super.onProgressChanged(view, newProgress);
//                    }
//                });
//            }
        }
    };

    //private CourseDetailSubjectApt courseDetailSubjectApt;
    private CourseDetailRvSubjectApt courseDetailSubjectApt;
    private ArrayList<CourseDetailSubjectBean.RowsBean> rowscourseList = new ArrayList<>();
    private Timer timer1;

    private SensorManager sensorManager;
    private Jzvd.JZAutoFullscreenListener sensorEventListener;

    @Override
    public int getLayoutId() {
        return R.layout.activity_specified_learning_course_details_again;
    }

    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.img_playorpause) {
            toggle();
        } else if (id == R.id.img_Courseback) {
            SharedPreferences sp = getSharedPreferences("SpecifiedLearningCourseDetailsAgainActivity",
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sp.edit();
            edit.clear();
            edit.commit();
            timerTask.cancel();
            timer1.cancel();
            timerTask = null;
            timer1 = null;
            finish();
        }
    }

    private String getStringTime(int cnt) {
        int hour = cnt / 3600;
        int min = cnt % 3600 / 60;
        int second = cnt % 60;
        return String.format(Locale.CHINA, "%02d:%02d:%02d", hour, min, second);
    }

    @Override
    public void initData() {
        web = (WebView) findViewById(R.id.wb_course);
        le_parement = (LinearLayout) findViewById(R.id.le_couse);
        img_Courseback = (ImageView) findViewById(R.id.img_Courseback);
        lv_coursedetail = (RecyclerView) findViewById(R.id.lv_coursedetail);
        jcVideoPlayerStandard = (MyJZVideoPlayerStandard) findViewById(R.id.videoplayer);
        tv_courseName = (TextView) findViewById(R.id.tv_course);
        tv_courseLength = (TextView) findViewById(R.id.tv_course2);
        tv_cumulativeLength = (TextView) findViewById(R.id.tv_course3);
        show_camera_iv = (ImageView) findViewById(R.id.id_show_camera_iv);
        show_camera_iv1 = (ImageView) findViewById(R.id.id_show_camera_iv1);
        tv_sure = (TextView) findViewById(R.id.tv_course10);
        tv_save = (TextView) findViewById(R.id.tv_course12);
        re_course = (RelativeLayout) findViewById(R.id.re_course);
        re_course1 = (LinearLayout) findViewById(R.id.le_course);
        img_course = (TextView) findViewById(R.id.img_course1);
        tv_course11 = (TextView) findViewById(R.id.tv_course11);
        re_course2 = (RelativeLayout) findViewById(R.id.re_course2);
        playOrPauseFab = (ImageView) findViewById(R.id.img_playorpause);
        tv_playorpause = (TextView) findViewById(R.id.tv_playorpause);
        progress_tv = (TextView) findViewById(R.id.progress_tv);
        total_tv = (TextView) findViewById(R.id.total_tv);
        scroll_view = (ScrollView) findViewById(R.id.scrollView);
        le_course2 = (LinearLayout) findViewById(R.id.le_course2);
        tv_course13 = (TextView) findViewById(R.id.tv_course13);
        tv_course14 = (TextView) findViewById(R.id.tv_course14);
        mSuperFileView = (SuperFileView2) findViewById(R.id.mSuperFileView);
        musicSeekBar=(SeekBar)findViewById(R.id.music_seekbar);

        le_course2.setVisibility(View.INVISIBLE);
        tv_course13.setVisibility(View.INVISIBLE);
        tv_course14.setVisibility(View.INVISIBLE);

        web.getSettings().setSavePassword(false);
        web.getSettings().setSaveFormData(false);
        web.removeJavascriptInterface("accessibility");
        web.removeJavascriptInterface("accessibilityTraversal");
        web.getSettings().setAllowFileAccessFromFileURLs(false);
        web.getSettings().setJavaScriptEnabled(true);
        web.setHorizontalScrollBarEnabled(false);//水平不显示
        web.setVerticalScrollBarEnabled(false); //垂直不显示
        web.setWebViewClient(new WebViewClient() {
            /*
            此处能拦截超链接的url,即拦截href请求的内容。
            */
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                JSImgUtil.setWebImageClick(view, JSImgUtil.JSCALLJAVA);
                super.onPageFinished(view, url);
            }
        });
        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#1F80C4"));

        musicHandler = new MusicHandler();
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorEventListener = new Jzvd.JZAutoFullscreenListener();
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);

        timer1 = new Timer();

        Bundle bundle = getIntent().getExtras();
        //通过name关键字取出用户名
        int tcsn = bundle.getInt("tcsn");
        SharedPreferences sp = getSharedPreferences("SpecifiedLearningCourseDetailsAgainActivity",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putInt("tcsn", tcsn);
        edit.commit();


        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                //在子线程中执行任务，执行完成或需要通知UI线程时调用以下方法
                mHandler.sendEmptyMessage(0);
            }
        });
        thread.start();


//         Thread thread1 = new Thread(new Runnable() {
//             @Override
//             public void run() {
//                 //在子线程中执行任务，执行完成或需要通知UI线程时调用以下方法
//                 mHandler.sendEmptyMessage(1);
//             }
//         });
//         thread1.start();
        initSeekba();//语音播放ui
    }

    private void initSeekba() {

        musicSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                int musicDuration = mediaPlayer.getDuration();
                if (musicDuration == -1) return;

                if (musicDuration < 0) {
                    progress_tv.setText(MusicUtils.getTime(0));
                    total_tv.setText(MusicUtils.getTime(0));
                } else {
                    progress_tv.setText(MusicUtils.getTime(progress));
                    total_tv.setText(MusicUtils.getTime(musicDuration));
                }
                //  LogUtils.e("musicSeekBar",musicDuration+"");

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int musicDuration = mediaPlayer.getDuration();
                if (musicDuration == -1) return;
                int progress = seekBar.getProgress();
                mediaPlayer.seekTo(progress);
                mediaPlayer.start();
                progress_tv.setText(MusicUtils.getTime(progress));
                total_tv.setText(MusicUtils.getTime(musicDuration));
            }
        });


        initMusicPlayer();
    }

    public void initMusicPlayer() {
        musicPrepared();
        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnErrorListener(this);

    }

    public void toggle() {
        if (tv_playorpause.getText().toString().trim().equals("播放")) {
            pause();
        } else if (tv_playorpause.getText().toString().trim().equals("暂停")) {
            start();
        }
    }

    public void start() {
        //     musicPrepared();
        mediaPlayer.start();
        musicHandler.sendEmptyMessage(0);
        playOrPauseFab.setImageResource(R.mipmap.play);
        tv_playorpause.setText("播放");
        //  isPlaying = true;

    }

    public void pause() {
        mediaPlayer.pause();
        musicHandler.removeMessages(0);
        playOrPauseFab.setImageResource(R.mipmap.stop);
        tv_playorpause.setText("暂停");
        //   isPlaying = false;
        //   fmm.stop();
    }

    private void updateProgress() {
        int musicDuration = mediaPlayer.getDuration();
        LogUtils.e("musicDuration", musicDuration + "");
        if (musicDuration == -1) return;
        int musicProgress = mediaPlayer.getCurrentPosition();
        musicSeekBar.setProgress(musicProgress);
        musicSeekBar.setMax(musicDuration);
        //     fmm.setProgress(musicProgress * 100 / musicDuration);
    }

    private void musicPrepared() {
        try {
            //   AssetFileDescriptor afd = getAssets().openFd("99nights.mp3");
            if (mediaPlayer != null) {
                mediaPlayer.reset();
                mediaPlayer = null;
            }
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            SharedPreferences sp = getSharedPreferences("SpecifiedLearningCourseDetailsAgainActivity",
                    Context.MODE_PRIVATE);
            String accessAudioUrl = sp.getString("accessAudioUrl", "");
            if (accessAudioUrl.equals("")) {
                // showToast("语音文件是空");
                return;
            }
            Uri uri = Uri.parse(accessAudioUrl);
            mediaPlayer.setDataSource(SpecifiedLearningCourseDetailsAgainActivity.this, uri);
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(this);

            musicHandler.sendEmptyMessage(0);
            playOrPauseFab.setImageResource(R.mipmap.play);
            tv_playorpause.setText("播放");
//            int duration = mediaPlayer.getDuration();
//            total_tv.setText(MusicUtils.getTime(duration));//刚开始获取时长
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        complete(mp);
    }

    public void complete(MediaPlayer mp) {
        //   isPlaying = false;
        mp.stop();
        musicHandler.removeMessages(0);
        playOrPauseFab.setImageResource(R.mipmap.stop);
        tv_playorpause.setText("暂停");
//        fmm.stop();
//        fmm.setProgress(100);
        musicPrepared();
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        LogUtils.e("MMP", "Media player error: what=" + what + ", extra=" + extra);
        return false;
    }

    public class MusicHandler extends Handler {

        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            updateProgress();
            sendEmptyMessageDelayed(0, 1000);
        }
    }

    @Override
    public void requestData() {
        initcourseData();//根据课程序列号查询课程详情
        initcoursesubject(); //根据课程序列号查询测验题
    }

    //根据课程序列号查询测验题
    private void initcoursesubject() {
        SharedPreferences sp = getSharedPreferences("SpecifiedLearningCourseDetailsAgainActivity",
                Context.MODE_PRIVATE);
        int tcsn = sp.getInt("tcsn", 0);
        RequestParams params = new RequestParams(AppInterfaceConfig.BASE_URL + "course/question/" + tcsn);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                CourseDetailSubjectBean courseDetailSubjectBean = JSON.parseObject(result, CourseDetailSubjectBean.class);
                List<CourseDetailSubjectBean.RowsBean> rows = courseDetailSubjectBean.getRows();
                if (rows.size() == 0) {
                    lv_coursedetail.setAdapter(null);
                    tv_course11.setVisibility(View.GONE);
                    return;
                }
                rowscourseList.clear();
                rowscourseList.addAll(rows);
                tv_course11.setVisibility(View.VISIBLE);
                //courseDetailSubjectApt = new CourseDetailSubjectApt(SpecifiedLearningCourseDetailsAgainActivity.this, rowscourseList, R.layout.course_detail_item);
                RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(SpecifiedLearningCourseDetailsAgainActivity.this);
                lv_coursedetail.setLayoutManager(layoutManager);
                courseDetailSubjectApt = new CourseDetailRvSubjectApt(SpecifiedLearningCourseDetailsAgainActivity.this, rowscourseList);
                lv_coursedetail.setAdapter(courseDetailSubjectApt);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                showToast("网络连接错误");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    //根据课程序列号查询课程详情
    private void initcourseData() {
        SharedPreferences sp = getSharedPreferences("SpecifiedLearningCourseDetailsAgainActivity",
                Context.MODE_PRIVATE);
        int tcsn = sp.getInt("tcsn", 0);
        RequestParams params = new RequestParams(AppInterfaceConfig.BASE_URL + "course/course/" + tcsn);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                CourseDetailBean courseDetailBean = JSON.parseObject(result, CourseDetailBean.class);
                CourseDetailBean.DataBean coursedata = courseDetailBean.getData();
                String courseName = coursedata.getCourseName();//课程名称
                if (courseName != null) {
                    tv_courseName.setText(courseName);
                }

                int courseLength = coursedata.getCourseLength();//课程时长
                SharedPreferences sp = getSharedPreferences("SpecifiedLearningCourseDetailsAgainActivity",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.putInt("courseLength", courseLength);
                editor.commit();
                tv_courseLength.setText("课程时长:" + courseLength + "分钟");
                String courseContent = coursedata.getCourseContent();
                if (courseContent != null) {
                    String[] imgs = JSImgUtil.returnImageUrlsFromHtml(coursedata.getCourseContent());
                    if (imgs != null) {
                        web.addJavascriptInterface(new ImageJavascriptInterface(SpecifiedLearningCourseDetailsAgainActivity.this, imgs), JSImgUtil.JSCALLJAVA);
                    }
                    new Thread(new runn(courseContent)).start();
                }

                //PDF文件查看
                String fileUrl = coursedata.getFileUrl();
                String fileName = coursedata.getFileName();
                if (fileUrl != null) {
                    mSuperFileView.setVisibility(View.VISIBLE);
                    mSuperFileView.setOnGetFilePathListener(new SuperFileView2.OnGetFilePathListener() {
                        @Override
                        public void onGetFilePath(SuperFileView2 mSuperFileView2) {
                            String path = FileParseUtil.getFilePath(mSuperFileView2, fileUrl, fileName);
                            if (path.contains("http")) {//网络地址要先下载
                                showAlertDialog(mSuperFileView2, fileUrl);
                            } else {
                                mSuperFileView2.displayFile(new File(path));
                            }
                        }
                    });
                    mSuperFileView.show();
                }

                //视频地址
                String accessVideoUrl = coursedata.getAccessVideoUrl();
                video(accessVideoUrl);

                //音频地址
                String accessAudioUrl = coursedata.getAccessAudioUrl();
                Audio(accessAudioUrl);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                showToast("网络连接错误");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    private String getNewContent(String htmltext) {
        Document doc = Jsoup.parse(htmltext);
        Elements elements = doc.getElementsByTag("img");
        for (Element element : elements) {
            element.attr("width", "100%").attr("height", "auto");
        }

        return doc.toString();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("value");
            String html = "<html><body>" + val + "</body></html>";
            web.loadDataWithBaseURL(null,
                    getNewContent(html), "text/html", "utf-8",
                    null);
        }
    };

    /**
     * 网络操作相关的子线程
     */
    public class runn implements Runnable {
        String vv;

        public runn(String vv) {
            this.vv = vv;
        }

        @Override
        public void run() {
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("value", vv);
            msg.setData(data);
            handler.sendMessage(msg);
        }
    }

    private void Audio(String accessAudioUrl) {

        if (accessAudioUrl == null) {
            re_course2.setVisibility(View.GONE);

            return;
        }
        re_course2.setVisibility(View.VISIBLE);
        SharedPreferences sp = getSharedPreferences("SpecifiedLearningCourseDetailsAgainActivity",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("accessAudioUrl", accessAudioUrl);
        editor.commit();

    }

    private void video(String accessVideoUrl) {
        if (accessVideoUrl == null) {
            jcVideoPlayerStandard.setVisibility(View.GONE);
            return;
        }
        jcVideoPlayerStandard.setVisibility(View.VISIBLE);
        HashMap headers = new HashMap<String, String>();
        headers.put("Referer", AppInterfaceConfig.BASE_URL);
        JZDataSource jzDataSource = new JZDataSource(accessVideoUrl, "", headers);
        jcVideoPlayerStandard.setUp(jzDataSource, jcVideoPlayerStandard.SCREEN_NORMAL);
        //jcVideoPlayerStandard.setUp(accessVideoUrl, "",jcVideoPlayerStandard.SCREEN_NORMAL, JZMediaIjk.class);
        Picasso.with(getApplicationContext()).load(R.mipmap.video)
                .into(jcVideoPlayerStandard.thumbImageView);
        JzvdStd.progressBar.setEnabled(false);//禁止拖动

    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        SharedPreferences sp = getSharedPreferences("SpecifiedLearningCourseDetailsAgainActivity",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.clear();
        edit.commit();
        timerTask.cancel();
        timer1.cancel();
        timerTask = null;
        timer1 = null;
        finish();
        //super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (sensorManager != null) {
            sensorManager.unregisterListener(sensorEventListener);
        }
        Jzvd.resetAllVideos();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        FileParseUtil.releaseFileView();
        mHandler.removeCallbacksAndMessages(null);
        if (musicHandler != null) {
            musicHandler.removeMessages(0);//语音播放器释放
            mediaPlayer.release();//语音播放器释放资源
        }
        Jzvd.resetAllVideos();
    }

    private void showAlertDialog(SuperFileView2 superFileView2, String url) {
        //1、使用Dialog、设置style
        //2、设置布局

        View contentView = LayoutInflater.from(SpecifiedLearningCourseDetailsAgainActivity.this).inflate(R.layout.dialog_circle, null);
        mDownloadPopWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);

        mDownloadPopWindow.setContentView(contentView);
        mDownloadPopWindow.setFocusable(false);
        mDownloadPopWindow.setOutsideTouchable(false);
        mDownloadPopWindow.showAtLocation(contentView, Gravity.CENTER, 0, 0);


        CircularProgressView circularProgressView = contentView.findViewById(R.id.circleProgress);
        TextView textView = contentView.findViewById(R.id.progressTxt);
        TextView textView1 = contentView.findViewById(R.id.hintTxt);

        jumpingBeans2 = JumpingBeans.with(textView1)
                .makeTextJump(0, textView1.getText().length())
                .setIsWave(true)
                .setLoopDuration(3000)
                .build();

        downLoadFromNet(url, superFileView2, circularProgressView, textView);
    }

    private void downLoadFromNet(final String url, final SuperFileView2 superFileView, CircularProgressView circularProgressView, TextView tv1) {
        //showLoadingDialog("文件下载中...");
        //1.网络下载、存储路径、
        File cacheFile = FileParseUtil.getCacheFile(url);
        if (cacheFile.exists()) {
            if (cacheFile.length() <= 0) {
                cacheFile.delete();
                return;
            }
        }

        OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).build();
        Request request = new Request.Builder().get().url(url).build();
        okHttpClient.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功,从服务器的响应对象中获取apk,流(服务器 输入流(提供数据)  本地 输出流(写入文件))
                ResponseBody body = response.body();
                //告知progressDialog总进度,不变
                //progressDialog.setMax((int) body.contentLength());
                final int allLength = (int) body.contentLength();
                //inputStream就是服务器把需要下载的apk以流的形式提供给客户端
                InputStream inputStream = body.byteStream();

                String fileName = url.substring(url.lastIndexOf("/"));
                String directory = Environment.getExternalStoragePublicDirectory
                        (Environment.DIRECTORY_DOWNLOADS).getPath();
                //File file = new File(directory+fileName);

                File file = FileParseUtil.getCacheFile(url);
                FileOutputStream fos = new FileOutputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                int temp = 0;//用于记录目前下载的到的位置
                while ((len = inputStream.read(bytes)) != -1) {
                    //将读过的数据写入文件中
                    fos.write(bytes, 0, len);
                    //告知progressDialog在下载过程中的当前进度
                    temp += len;
                    //将当前的下载位置,设置给progressDialog
                    //progressDialog.setProgress(temp);
                    //没下载一段数据,睡眠一段时间

                    int progress = (int) (temp * 100.0 / allLength);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            circularProgressView.setProgress(progress);
                            tv1.setText(progress + "%");
                        }
                    });

                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //2.ACache记录文件的有效期
                        mDownloadPopWindow.dismiss();
                        superFileView.displayFile(file);
                    }
                });
            }
        });
    }
}
